package com.shwread.android.qysw.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000152.R;
import com.shwread.android.ui.customview.BadgeView;
import com.shwread.android.ui.customview.MyListView;
import com.shwread.android.ui.widget.LoadingView;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase.OnRefreshListener;
import com.shwread.http.base.ObjectHttpResponseHandler;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import logic.bean.GoodsBaseInfo;
import logic.bean.GoodsInfoColumn;
import logic.bean.PageDto;
import logic.constants.DefaultConsts;
import logic.dao.ShoppingCartDao;
import logic.util.MoneyUtil;
import logic.util.PicassoUtil;
import logic.util.Utils;


public class GoodsBoxActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener
{
	private Context                 context;
	private TextView                tvTitle;
	private Button                  butBack, butHome;
	
	private MyListView              lv;
	private PullToRefreshScrollView psView;
	private ImageView               ivAddShoppingCar;
	
	private LinearLayout            llEmpty;
	private LoadingView             loadingView;
	
	private GoodsBoxAdapter         goodsBoxAdapter;
	private GoodsInfoColumn         goodsInfoColumn;
	private List<GoodsBaseInfo>     goodsList;
	private PageDto                 pageDto;
	
	private Intent                  oldIntent;
	private long                    sortItemId;
	private String                  sortItemName;
	private int                     page      = 1;
	private int                     pagNum    = 5;
	private boolean                 isRefresh = true;                       //是否刷新 true:刷新 false:加载
	                                                                         
	private static final int        red       = Color.parseColor("#ff3300");
	private BadgeView               badgeView;
	
	private Handler                 handler   = new Handler()
	                                          {
		                                          @Override
		                                          public void handleMessage(Message msg) {
			                                          
		                                          }
	                                          };
	
	@Override
	public Handler getUIHandler() {
		// TODO Auto-generated method stub
		return handler;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.goods_box);
		context = this;
		oldIntent = getIntent();
		
		findView();
		addListener();
		initData();
		initLoadingView();
	}
	
	@Override
	protected void onResume() {
	    // TODO Auto-generated method stub
	    super.onResume();
		getShoppingCartCount();
	}
	
	private void initLoadingView() {
		loadingView.setLoadingAnim(R.anim.home_progress);
		loadingView.changeLoadingStatus(0);
	}
	
	private void findView() {
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		butBack = (Button) findViewById(R.id.common_header_back);
		butHome = (Button) findViewById(R.id.common_header_home);
		tvTitle.setText("");
		butBack.setVisibility(View.VISIBLE);
		butHome.setVisibility(View.VISIBLE);
		loadingView = (LoadingView) findViewById(R.id.goods_box_loading_view);
		psView = (PullToRefreshScrollView) findViewById(R.id.good_box_psview);
		lv = (MyListView) findViewById(R.id.good_box_list);
		loadingView.setVisibility(View.VISIBLE);
		psView.setVisibility(View.GONE);
		ivAddShoppingCar = (ImageView) findViewById(R.id.good_box_add_shopping_car_iv);
		
		badgeView = new BadgeView(context, ivAddShoppingCar);
		badgeView.setTextSize(10);
		badgeView.setBadgePosition(2);// 2代表右上角
		badgeView.setBackgroundResource(R.drawable.red_radio);
		badgeView.setTextColor(context.getResources().getColor(android.R.color.white));
		badgeView.show();
		
		llEmpty = (LinearLayout) findViewById(R.id.ll_goods_box_empty);
		llEmpty.setVisibility(View.GONE);
	}
	
	private void addListener() {
		butBack.setOnClickListener(this);
		butHome.setOnClickListener(this);
		ivAddShoppingCar.setOnClickListener(this);
		
		PullToRefreshUtil.initLabel(context, psView);
		
		psView.setOnRefreshListener(new OnRefreshListener<ScrollView>()
		{
			
			@Override
			public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
				if (psView.isFooterShown())
				{
					loadMore();
				}
				else if (psView.isHeaderShown())
				{
					refrush();
				}
				
			}
			
		});
		
		lv.setOnItemClickListener(new OnItemClickListener()
		{
			
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				//				Intent intent = new Intent(GoodsBoxActivity.this, GoodsMainActivity.class);
				Intent intent = new Intent(GoodsBoxActivity.this, NewGoodsMainActivity.class);
				
				intent.putExtra(DefaultConsts.GOODS_ID_TO_WAP, goodsInfoColumn.getGoodsList().get(position).getGoodsId());
				intent.putExtra(DefaultConsts.GOODS_DETAIL_URL_TO_WAP, goodsInfoColumn.getGoodsList().get(position).getDetailUrl());
				intent.putExtra(DefaultConsts.GOODS_BASE_URL_TO_WAP, goodsInfoColumn.getGoodsList().get(position).getBaseUrl());
				startActivity(intent);
			}
		});
		
	}
	
	/**
	 * 上拉加载更多
	 */
	private void loadMore() {
		if (pageDto == null)
		{
			getSortData();
		}
		else if (page < pageDto.getTotalPage())
		{
			PullToRefreshUtil.setLoadLabel(psView, "加载更多");
			getSortData();
		}
		else
		{
			PullToRefreshUtil.setLoadLabel(psView, "没有更多数据了");
			handler.postDelayed(new Runnable()
			{
				
				@Override
				public void run() {
					psView.onRefreshComplete();
					
				}
			}, 500);
		}
		
	}
	
	/**
	 * 下拉刷新
	 */
	private void refrush() {
		page = 1;
		isRefresh = true;
		getSortData();
		
	}
	
	/**
	 * 获取购物车信息
	 */
	private void getShoppingCartCount() {
		ShoppingCartDao shoppingCartDao = ShoppingCartDao.getInstance(context);
		long count = shoppingCartDao.queryCount(ActionHelp.getAccount());
		if (count <= 0)
		{
			badgeView.hide();
		}
		else
		{
			badgeView.setText(String.valueOf(count));
			badgeView.show();
		}
	}
	
	private void initData() {
		goodsList = new ArrayList<GoodsBaseInfo>();
		goodsBoxAdapter = new GoodsBoxAdapter();
		lv.setAdapter(goodsBoxAdapter);
		try
		{
			oldIntent = getIntent();
			if (oldIntent.getExtras().getInt(DefaultConsts.FROM_TYPE) == DefaultConsts.ECOMMERCE_TAG_FROM_SORT)
			{
				sortItemId = oldIntent.getExtras().getLong(DefaultConsts.ECOMMERCE_SORT_TYPE);
				sortItemName = oldIntent.getExtras().getString(DefaultConsts.ECOMMERCE_SORT_NAME);
				tvTitle.setText(Utils.isEmpty(sortItemName) ? "" : sortItemName);
				getSortData();
			}
		}
		catch (Exception e)
		{
			// TODO: handle exception
		}
		
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_back:
				finish();
				break;
			case R.id.common_header_home:
				//				Utils.showToast(context, "您选择了返回主页面");
				//				startActivity(new Intent(GoodsBoxActivity.this, MainActivity.class));
				//调试数据
				//				startActivity(new Intent(this, MainActivity.class));
				BaseSimpleActivity.gotoMainActivity();
				break;
			case R.id.good_box_add_shopping_car_iv:
				//				Utils.showToast(context, "您点击了购物车");
				startActivity(new Intent(GoodsBoxActivity.this, ShoppingCartActivity.class));
				break;
			default:
				break;
		}
		
	}
	
	private void getSortData() {
		
		ActionHelp.qryGoodsByItemId(context, sortItemId, page, pagNum, new ObjectHttpResponseHandler<GoodsInfoColumn>()
		{
			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				Utils.ToastShow(context, "加载失败 ");
				System.out.println("xxxxxxxxxxxxxxxx_onFailure" + responseString);
				psView.onRefreshComplete();
			}
			
			@Override
			public void onSuccess(int statusCode, Header[] headers, GoodsInfoColumn object, String responseString) {
				System.out.println("xxxxxxxxxxxxxxxx_onSuccess" + responseString);
				loadingView.setVisibility(View.GONE);
				psView.setVisibility(View.VISIBLE);
				goodsInfoColumn = object;
				if (isRefresh)
				{
					pageDto = goodsInfoColumn.getPageDto();
					goodsList = goodsInfoColumn.getGoodsList();
					if (goodsList == null || goodsList.size() == 0)
					{
						psView.setVisibility(View.GONE);
						llEmpty.setVisibility(View.VISIBLE);
					}
					isRefresh = false;
					PullToRefreshUtil.setLoadLabel(psView, "加载更多");
				}
				else
				{
					goodsList.addAll(goodsInfoColumn.getGoodsList());
					page++;
					if (goodsList == null || goodsList.size() == 0)
					{
						psView.setVisibility(View.GONE);
						llEmpty.setVisibility(View.VISIBLE);
					}
				}
				goodsBoxAdapter.notifyDataSetChanged();
				psView.onRefreshComplete();
			}
			
			@Override
			public Type getType() {
				// TODO Auto-generated method stub
				return new TypeToken<GoodsInfoColumn>()
				{
				}.getType();
			}
		});
		
	}
	
	private class GoodsBoxAdapter
	        extends
	        BaseAdapter
	{
		
		@Override
		public int getCount() {
			
			return (goodsInfoColumn == null || goodsInfoColumn.getGoodsList().size() == 0) ? 0 : goodsInfoColumn.getGoodsList().size();
		}
		
		@Override
		public Object getItem(int position) {
			
			return (goodsInfoColumn == null || goodsInfoColumn.getGoodsList().size() == 0) ? null : goodsInfoColumn.getGoodsList().get(position);
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder;
			if (convertView == null)
			{
				viewHolder = new ViewHolder();
				convertView = LayoutInflater.from(context).inflate(R.layout.goods_box_list_item, parent, false);
				//				convertView = getLayoutInflater().inflate(R.layout.goods_box_list_item2, null);
				viewHolder.ivGoodsCover = (ImageView) convertView.findViewById(R.id.good_box_list_item_cover_iv);
				viewHolder.tvGoodIntro = (TextView) convertView.findViewById(R.id.good_box_list_item_intro_tv);
				viewHolder.tvDiscountPrice = (TextView) convertView.findViewById(R.id.good_box_list_item_discount_price_tv);
				viewHolder.tvOriginalPrice = (TextView) convertView.findViewById(R.id.good_box_list_item_original_price_tv);
				viewHolder.tvSaleNumber = (TextView) convertView.findViewById(R.id.good_box_list_item_number_tv);
				
				convertView.setTag(viewHolder);
			}
			else
			{
				viewHolder = (ViewHolder) convertView.getTag();
			}
			
			GoodsBaseInfo info = (GoodsBaseInfo) getItem(position);
			viewHolder.tvGoodIntro.setText(info.getTitle());
			//如果为空显示默认图片
			if (Utils.isEmpty(info.getCoverUrl()))
			{
				viewHolder.ivGoodsCover.setBackgroundResource(R.drawable.bg_small_image);
			}
			else
			{
				PicassoUtil.load(GoodsBoxActivity.this, info.getCoverUrl(), R.drawable.bg_small_image, viewHolder.ivGoodsCover);
			}
			//如果活动价为0，说明该商品没有参加活动，只显示原价
			if (info.getActivityPrice() == 0)
			{
				viewHolder.tvDiscountPrice.setText(" ¥" + Utils.getMoneyFormat(MoneyUtil.divide(info.getSalePrice(), 100.0)));
				viewHolder.tvOriginalPrice.setVisibility(View.GONE);
			}
			else
			{
				viewHolder.tvDiscountPrice.setText(" ¥" + Utils.getMoneyFormat(MoneyUtil.divide(info.getActivityPrice(), 100.0)));
				viewHolder.tvOriginalPrice.setText(" ¥" + Double.toString(info.getSalePrice()));
				viewHolder.tvOriginalPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//设置中画线
				viewHolder.tvOriginalPrice.setVisibility(View.VISIBLE);
				
			}
			if (info.getSaleNum() == 0)
			{
				viewHolder.tvSaleNumber.setText("新品上市");
			}
			else
			{
				viewHolder.tvSaleNumber.setText(Long.toString(info.getSaleNum()) + "人已经购买");
			}
			
			return convertView;
		}
	}
	
	class ViewHolder
	{
		private ImageView ivGoodsCover;   //商品封面URL
		private TextView       tvGoodIntro;    //商品介绍
		private TextView       tvDiscountPrice; //商品打折后的价格
		private TextView       tvOriginalPrice; //商品原价
		private TextView       tvSaleNumber;   //商品卖出的数量
	}
	
}
